package com.semlab.client.fwk.ap;

import java.util.ArrayList;

import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.place.shared.PlaceChangeEvent;
import com.google.gwt.place.shared.PlaceChangeRequestEvent;

@Deprecated
public abstract class CustomActivityManager extends ActivityManager {

	protected String containerId;

	public CustomActivityManager(String containerId, ActivityMapper mapper, com.google.web.bindery.event.shared.EventBus eventBus) {
		super(mapper, eventBus);
		this.containerId = containerId;
	}
	
	/**
	 * This way of handling causes url to remain unchanged
	 */
	protected abstract boolean isPlaceChangeAllowed(Place place);

	@Override
	public final void onPlaceChange(PlaceChangeEvent event) {
		Place place = (Place) event.getNewPlace();
		
			if (isPlaceChangeAllowed(place) && canPropagate(event.getNewPlace())) {
				super.onPlaceChange(event);
			}
	}

	@Override
	public final void onPlaceChangeRequest(PlaceChangeRequestEvent event) {
		if (canPropagate(event.getNewPlace())) {
			super.onPlaceChangeRequest(event);
		}
	}

	/**
	 * @param place
	 * @return boolean
	 * 
	 *         Method checks if place of any of its parameters has container id
	 *         that matches current activity manager
	 */
	protected boolean canPropagate(com.google.gwt.place.shared.Place newPlace) {
		if (newPlace instanceof Place) {
			Place mbPlace = (Place) newPlace;
			ArrayList<String> allowedContainers = new ArrayList<String>();
			allowedContainers.add(mbPlace.getContainerId());
			if (mbPlace.getParameterPlaces().size() > 0) {
				ArrayList<Place> places = mbPlace.getParameterPlaces();
				for (Place place : places) {
					allowedContainers.add(place.getContainerId());
				}
			}
			if (allowedContainers.contains(containerId)) {
				// GWT.log(":: propagation check = true");
				return true;
			}
		}
		return false;

	}
}
